<template>
  <div>
    <el-form :model="sysPermissionSearch" inline ref="searchFormRef">
      <el-form-item label="菜单名称" prop="permissionName">
        <el-input v-model="sysPermissionSearch.permissionName"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="sysPermissionSearch.status"
            placeholder="请选择状态"
            style="width: 240px"
        >
          <el-option label="正常" :value="0"/>
          <el-option label="禁用" :value="1"/>
          <el-option label="全部" :value="-1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getSysPermissionList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" type="primary" @click="resetSearch(searchFormRef)"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-space wrap>
      <el-button :icon="Plus" size="small" type="primary" @click="addSysPermission(0)"
      >新增
      </el-button>
      <el-button :icon="Download" size="small">导入</el-button>
      <el-button :icon="Upload" size="small">导出</el-button>
    </el-space>
    <el-table :data="sysPermissionList" row-key="permissionId">
      <el-table-column prop="permissionId" label="编号"/>
      <el-table-column prop="permissionName" label="名称"/>
      <el-table-column label="图标">
        <template #default="scope">
          <component
              :is="scope.row.icon"
              class="icon-size"
              v-if="scope.row.icon"
          ></component>
        </template>
      </el-table-column>
      <el-table-column prop="permissionKey" label="标识"/>
      <el-table-column prop="component" label="组件"/>
      <el-table-column prop="path" label="全路由"/>
      <el-table-column prop="url" label="路径"/>
      <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat"/>
      <el-table-column label="操作" width="220px">
        <template #default="scope">
          <div class="flex-hcenter">
            <el-button :icon="EditPen" size="small" type="warning" @click="modifySysPermission(scope.row.permissionId)">
              修改
            </el-button>
            <el-divider direction="vertical"/>
            <el-button :icon="Plus" size="small" type="primary" @click="addSysPermission(scope.row.permissionId)">新增
            </el-button>
            <el-divider direction="vertical"/>
            <el-button :icon="Delete" size="small" type="danger" @click="deleteSysPermission(scope.row.permissionId)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogIsAdd ? '新增' : '修改'"
        width="600"
        draggable
        @close="resetForm(ruleFormRef)"
    >
      <el-form :model="sysPermission" label-width="100" :rules="rules" ref="ruleFormRef">
        <el-form-item label="图标" prop="icon">
          <el-input v-model="sysPermission.icon"></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionKey">
          <el-input v-model="sysPermission.permissionKey" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="sysPermission.permissionName"></el-input>
        </el-form-item>
        <el-form-item label="父级" prop="parentId">
          <el-tree-select
              style="max-width: 500px"
              check-strictly
              node-key="permissionId"
              v-model="sysPermission.parentId"
              :data="sysPermissionFlode"
              :props="defaultProps"
              show-checkbox
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="permissionType">
          <el-radio-group v-model="sysPermission.permissionType">
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">页面</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="component">
          <template #label>
            <el-tooltip
                effect="dark"
                content="从home(不包括)目录下开始,不以/为开始"
                placement="top-start"
            >
              <el-text>
                组件位置
                <el-icon>
                  <QuestionFilled/>
                </el-icon>
              </el-text>
            </el-tooltip>
          </template>
          <el-input v-model="sysPermission.component"></el-input>
        </el-form-item>
        <el-form-item label="访问路由" prop="path">
          <template #label>
            <el-tooltip
                effect="dark"
                content="组件路由全路径，以/layout开始，多个单词以-分隔"
                placement="top-start"
            >
              <el-text>
                访问路由
                <el-icon>
                  <QuestionFilled/>
                </el-icon>
              </el-text>
            </el-tooltip>
          </template>
          <template #default>
            <el-input v-model="sysPermission.path"></el-input>
          </template>
        </el-form-item>
        <el-form-item label="路径" prop="url">
          <template #label>
            <el-tooltip
                effect="dark"
                content="路由子路径，不包括父路由路径,且不以/开头"
                placement="top"
            >
              <el-text>
                路径
                <el-icon>
                  <QuestionFilled/>
                </el-icon>
              </el-text>
            </el-tooltip>
          </template>
          <el-input v-model="sysPermission.url"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="sysPermission.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="sysPermission.isShow">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可关闭" prop="isClosable">
          <el-radio-group v-model="sysPermission.isClosable">
            <el-radio :value="0">可以关闭</el-radio>
            <el-radio :value="1">不可关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSysPermission(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from "vue";
import {
  Plus,
  Search,
  Refresh,
  EditPen,
  Delete,
  QuestionFilled,
  Download,
  Upload
} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useUserStore} from "@/stores/user";
import moment from "moment";
import type {FormInstance, FormRules} from "element-plus";
import type {SysPermission, SysPermissionTreeVO} from "@/api/system/permission/type";
import {
  reqGetSysPermissionTreeList,
  reqAddSysPermission,
  reqModifySysPermission,
  reqGetSysPermissionFolder,
  reqDeleteSysPermission,
  reqGetSysPermission,
} from "@/api/system/permission";

const userStore = useUserStore();
let sysPermissionList = ref<SysPermissionTreeVO[]>([]);
let sysPermissionFlode = ref<SysPermissionTreeVO[]>([
  {
    permissionId: 0,
    permissionKey: "",
    permissionName: "一级目录",
    parentId: 0,
    createTime: "",
    createBy: "",
    path: "",
    component: "",
    permissionType: 0,
    status: 0,
    remark: "",
    icon: "",
    url: "",
    isClosable: 0,
    isShow: 0,
    children: [],
  },
]);
let sysPermissionSearch = reactive({
  permissionName: "",
  status: -1,
});
let dialogIsAdd = ref<boolean>(true);
let dialogFormVisible = ref<boolean>(false);
let sysPermission = reactive<SysPermission>({
  permissionId: null,
  permissionKey: "",
  permissionName: "",
  parentId: 0,
  createTime: "",
  createBy: "",
  path: "",
  component: "",
  permissionType: 0,
  status: 0,
  remark: "",
  icon: "",
  url: "",
  isClosable: 0,
  isShow: 0,
});
const ruleFormRef = ref<FormInstance>();
let searchFormRef = ref<FormInstance>();
let rules = reactive<FormRules<SysPermission>>({
  permissionKey: [{required: true, message: "请输入权限标识", trigger: "blur"}],
  permissionName: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  parentId: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  permissionType: [{required: true, message: "请输入权限名称", trigger: "blur"}],
});

function resetSearch(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
}

function getSysPermissionList() {
  return reqGetSysPermissionTreeList(sysPermissionSearch).then((res) => {
    sysPermissionList.value = res.data;
  });
}

/**
 * 手动重置表单，新增和修改采用同一个表单，element-plus表单重置会出现bug
 * **/
function resetSysPermission() {
  sysPermission.permissionId = null;
  sysPermission.permissionKey = "";
  sysPermission.permissionName = "";
  sysPermission.parentId = 0;
  sysPermission.createTime = "";
  sysPermission.createBy = "";
  sysPermission.path = "";
  sysPermission.component = "";
  sysPermission.permissionType = 0;
  sysPermission.status = 0;
  sysPermission.remark = "";
  sysPermission.icon = "";
  sysPermission.url = "";
  sysPermission.isClosable = 1;
  sysPermission.isShow = 0;
}

/**
 * 重置表单
 * @param formEl
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

async function modifySysPermission(permissionId: number) {
  // 排除children属性（如果直接赋值会导致children新增在目标sysPermission身上，导致失去响应式)
  const res = await reqGetSysPermission(permissionId);
  Object.assign(sysPermission, res.data);
  dialogIsAdd.value = false;
  dialogFormVisible.value = true;
}

function addSysPermission(parentId: number) {
  sysPermission.parentId = parentId;
  dialogIsAdd.value = true; //表示新增dialog
  dialogFormVisible.value = true; //开启diaglog
}

let saveSysPermission = async (formEl: FormInstance | undefined) => {
  if (!formEl) return; //表单校验
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialogIsAdd.value) {
        await reqAddSysPermission(sysPermission);
      } else {
        await reqModifySysPermission(sysPermission);
        await getSysPermissionList();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
  dialogFormVisible.value = false;
  resetSysPermission(); //重置表单
};
const dateFormat = (row: any, column: any, cellValue: any) => {
  return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
};

function deleteSysPermission(permissionId: string | number) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteSysPermission(permissionId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
}

onMounted(() => {
  getSysPermissionList();
});

const defaultProps = {
  children: "children",
  label: "permissionName",
};
//弹窗打开权限获取数据
watch(dialogFormVisible, () => {
  if (dialogFormVisible.value) {
    // 如果弹窗是打开状态，那么就发送请求
    reqGetSysPermissionFolder().then((res) => {
      sysPermissionFlode.value[0].children = res.data;
    });
  }
});
</script>
<style lang="scss"></style>
